package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.Comment;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/showcomment")
public class CommentListServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Comment> list = new ArrayList<>();
        String msg = "未知错误";
        String aidStr = req.getParameter("aid");
        if(!StrUtil.isBlank(aidStr)){
            int aid = Integer.valueOf(aidStr);
            if(aid > 0){
                Connection connection = DBUtils.getConnection();
                String sql = "select comment.*,userinfo.* from comment join userinfo on comment.uid=userinfo.uid where aid=?";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setInt(1,aid);
                ResultSet resultSet = statement.executeQuery();
                while (resultSet.next()){
                    Comment comment = new Comment();
                    comment.setText(resultSet.getString("text"));
                    String createtime = resultSet.getString("createtime");
                    comment.setCreatetime(createtime.substring(0, createtime.lastIndexOf(".")));
                    comment.setUid(resultSet.getInt("uid"));
                    comment.setNickname(resultSet.getString("nickname"));
                    list.add(comment);
                }
                msg = "";
            }
            else {
                msg = "参数错误";
            }
        }
        else {
            msg = "非法参数";
        }

        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,list,msg)));
    }
}
